package com.offcn.sellergoods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.offcn.sellergoods.gruop.GoodsGroup;
import com.offcn.sellergoods.mapper.*;
import com.offcn.sellergoods.pojo.*;
import com.offcn.common.entity.PageResult;
import com.offcn.sellergoods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;
import java.util.Map;

/****
 * @Author:ujiuye
 * @Description:Goods业务层接口实现类
 * @Date 2021/2/1 14:19
 *****/
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    /**
     * 商品表
     */
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 商品扩展信息
     */
    @Autowired
    private GoodsDescMapper goodsDescMapper;

    /**
     * SUK
     */
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SellerMapper sellerMapper;

    /**
     * Goods条件+分页查询
     *
     * @param goods 查询条件
     * @param page  页码
     * @param size  页大小
     * @return 分页结果
     */
    @Override
    public PageResult<Goods> findPage(Goods goods, int page, int size) {
        Page<Goods> mypage = new Page<>(page, size);
        QueryWrapper<Goods> queryWrapper = this.createQueryWrapper(goods);
        IPage<Goods> iPage = this.page(mypage, queryWrapper);
        return new PageResult<Goods>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * Goods分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageResult<Goods> findPage(int page, int size) {
        Page<Goods> mypage = new Page<>(page, size);
        IPage<Goods> iPage = this.page(mypage, new QueryWrapper<Goods>());

        return new PageResult<Goods>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * Goods条件查询
     *
     * @param goods
     * @return
     */
    @Override
    public List<Goods> findList(Goods goods) {
        //构建查询条件
        QueryWrapper<Goods> queryWrapper = this.createQueryWrapper(goods);
        //根据构建的条件查询数据
        return this.list(queryWrapper);
    }


    /**
     * Goods构建查询对象
     *
     * @param goods
     * @return
     */
    public QueryWrapper<Goods> createQueryWrapper(Goods goods) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (goods != null) {
            // 主键
            if (!StringUtils.isEmpty(goods.getId())) {
                queryWrapper.eq("id", goods.getId());
            }
            // 商家ID
            if (!StringUtils.isEmpty(goods.getSellerId())) {
                queryWrapper.eq("seller_id", goods.getSellerId());
            }
            // SPU名
            if (!StringUtils.isEmpty(goods.getGoodsName())) {
                queryWrapper.eq("goods_name", goods.getGoodsName());
            }
            // 默认SKU
            if (!StringUtils.isEmpty(goods.getDefaultItemId())) {
                queryWrapper.eq("default_item_id", goods.getDefaultItemId());
            }
            // 状态
            if (!StringUtils.isEmpty(goods.getAuditStatus())) {
                queryWrapper.eq("audit_status", goods.getAuditStatus());
            }
            // 是否上架
            if (!StringUtils.isEmpty(goods.getIsMarketable())) {
                queryWrapper.eq("is_marketable", goods.getIsMarketable());
            }
            // 品牌
            if (!StringUtils.isEmpty(goods.getBrandId())) {
                queryWrapper.eq("brand_id", goods.getBrandId());
            }
            // 副标题
            if (!StringUtils.isEmpty(goods.getCaption())) {
                queryWrapper.eq("caption", goods.getCaption());
            }
            // 一级类目
            if (!StringUtils.isEmpty(goods.getCategory1Id())) {
                queryWrapper.eq("category1_id", goods.getCategory1Id());
            }
            // 二级类目
            if (!StringUtils.isEmpty(goods.getCategory2Id())) {
                queryWrapper.eq("category2_id", goods.getCategory2Id());
            }
            // 三级类目
            if (!StringUtils.isEmpty(goods.getCategory3Id())) {
                queryWrapper.eq("category3_id", goods.getCategory3Id());
            }
            // 小图
            if (!StringUtils.isEmpty(goods.getSmallPic())) {
                queryWrapper.eq("small_pic", goods.getSmallPic());
            }
            // 商城价
            if (!StringUtils.isEmpty(goods.getPrice())) {
                queryWrapper.eq("price", goods.getPrice());
            }
            // 分类模板ID
            if (!StringUtils.isEmpty(goods.getTypeTemplateId())) {
                queryWrapper.eq("type_template_id", goods.getTypeTemplateId());
            }
            // 是否启用规格
            if (!StringUtils.isEmpty(goods.getIsEnableSpec())) {
                queryWrapper.eq("is_enable_spec", goods.getIsEnableSpec());
            }
            // 是否删除
            if (!StringUtils.isEmpty(goods.getIsDelete())) {
                queryWrapper.eq("is_delete", goods.getIsDelete());
            }
        }
        return queryWrapper;
    }

    /**
     * 删除Goods
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        //通过id查询
        Goods goods = goodsMapper.selectById(id);
        //判断商品是否存在
        if (goods == null) {
            throw new RuntimeException("商品不存在");
        }
        //判断商品是否在上架状态
        if ("1".equals(goods.getIsMarketable())) {
            throw new RuntimeException("商品目前处于上架状态中，请先下架在进行删除");
        }
        goods.setIsDelete("1");
        //重新审核
        goods.setAuditStatus("0");
        goodsMapper.updateById(goods);

        //sku的删除
        Item item = new Item();
        item.setStatus("3");
        UpdateWrapper<Item> wrapper = new UpdateWrapper<>();
        wrapper.eq("goods_id", id);
        itemMapper.update(item, wrapper);

    }

    /**
     * 修改Goods
     *
     * @param goodsGroup
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(GoodsGroup goodsGroup) {
        Goods goods = goodsGroup.getGoods();
        GoodsDesc goodsDesc = goodsGroup.getGoodsDesc();

        goodsMapper.updateById(goods);
        goodsDescMapper.updateById(goodsDesc);

        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("goods_id", goods.getId());
        itemMapper.delete(itemQueryWrapper);

        //保存sku
        saveItem(goodsGroup, "updata");
    }

    /**
     * sku信息
     *
     * @param goodsGroup
     */
    private void saveItem(GoodsGroup goodsGroup, String falg) {
        Goods goods = goodsGroup.getGoods();
        List<Item> itemList = goodsGroup.getItemList();
        if ("1".equals(goods.getIsEnableSpec())) {
            //启用sku信息 -- sku信息  -- 从前端传入
            for (Item item : itemList) {

                String goodsName = goods.getGoodsName();
                String spec = item.getSpec();
                Map<String, String> map = JSON.parseObject(spec, Map.class);

                for (String key : map.keySet()) {
                    String value = map.get(key);
                    goodsName += " " + value;
                }

                item.setTitle(goodsName);
                item.setSellPoint(goodsName);
                item.setGoodsId(goods.getId());
                setItem(item, goodsGroup);

                if ("add".equals(falg)) {
                    item.setCreateTime(new Date());
                }
                itemMapper.insert(item);
            }
        } else {
            //不启用sku信息 -- sku信息  -- 从前端传入
            Item item = new Item();
            item.setTitle(goods.getGoodsName());
            item.setSellPoint(goods.getGoodsName());
            item.setGoodsId(goods.getId());

            item.setIsDefault("0");
            item.setNum(9999);
            item.setPrice(goods.getPrice());
            setItem(item, goodsGroup);
            item.setSpec("{}");
            item.setStatus("1");
            itemMapper.insert(item);
        }
    }

    /**
     * 增加Goods
     *
     * @param goodsGroup
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(GoodsGroup goodsGroup) {
        Goods goods = goodsGroup.getGoods();
        //未审核
        goods.setAuditStatus("0");
        //下架
        goods.setIsMarketable("0");
        //未删除
        goods.setIsDelete("0");
        GoodsDesc goodsDesc = goodsGroup.getGoodsDesc();


        //spu保存
        goodsMapper.insert(goods);
        goodsDesc.setGoodsId(goods.getId());
        goodsDescMapper.insert(goodsDesc);

        //sku保存
        saveItem(goodsGroup, "add");
    }

    private void setItem(Item item, GoodsGroup goodsGroup) {
        GoodsDesc goodsDesc = goodsGroup.getGoodsDesc();
        Goods goods = goodsGroup.getGoods();

        String itemImages = goodsDesc.getItemImages();
        List<Map> list = JSON.parseArray(itemImages, Map.class);
        if (list != null && list.size() > 0) {
            Map map = list.get(0);
            String url = (String) map.get("url");
            item.setItemSn(url);
        }

        item.setCategoryId(goods.getCategory3Id());

        item.setUpdateTime(new Date());

        ItemCat itemCat = itemCatMapper.selectById(goods.getCategory3Id());
        item.setCategory(itemCat.getName());

        Brand brand = brandMapper.selectById(goods.getBrandId());
        item.setBrand(brand.getName());

        Seller seller = sellerMapper.selectById(goods.getSellerId());
        item.setSeller(seller.getNickName());

    }

    /**
     * 根据ID查询Goods
     *
     * @param id
     * @return
     */
    @Override
    public GoodsGroup findById(Long id) {
        //sku数据
        Goods goods = goodsMapper.selectById(id);
        GoodsDesc goodsDesc = goodsDescMapper.selectById(id);

        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", id);
        queryWrapper.orderByDesc("is_default");
        List<Item> items = itemMapper.selectList(queryWrapper);

        GoodsGroup goodsGroup = new GoodsGroup();
        goodsGroup.setGoods(goods);
        goodsGroup.setItemList(items);
        goodsGroup.setGoodsDesc(goodsDesc);
        return goodsGroup;
    }

    /**
     * 查询Goods全部数据
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Goods> findAll() {
        return this.list(new QueryWrapper<Goods>());
    }

    /**
     * 商品审核操作
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public void audit(Long id, String status) {
        //根据id查询数据
        Goods goods = goodsMapper.selectById(id);
        //是否可以查到，可以查到后在判断删除状态
        if (goods != null && !"1".equals(goods.getIsDelete())) {
            //未删除状态，修改审核状态 ，在进行删除
            if ("1".equals(status)) {
                //商家
                goods.setIsMarketable("1");
            }
            goods.setAuditStatus(status);

            goodsMapper.updateById(goods);
        }
    }

    /**
     * 商品上架
     *
     * @param id
     * @return
     */
    @Override
    public void upMarkble(Long id) {
        //根据id查询数据
        Goods goods = goodsMapper.selectById(id);
        //判断是否查到，判断删除状态
        if (goods == null || "1".equals(goods.getIsDelete())) {
            throw new RuntimeException("商品不存在");
        }
        //判断审核状态
        if (!"1".equals(goods.getAuditStatus())) {
            throw new RuntimeException("商品未审核通过，不能上架");
        }
        //商品上架
        goods.setIsMarketable("1");
        goodsMapper.updateById(goods);

        //sku上架
        Item item = new Item();
        item.setStatus("1");
        UpdateWrapper<Item> wrapper = new UpdateWrapper<>();
        wrapper.eq("goods_id",id);
        itemMapper.update(item,wrapper);
    }

    /**
     * 商品下架
     *
     * @param id
     * @return
     */
    @Override
    public void lowerMarkble(Long id) {
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            throw new RuntimeException("商品不存在!");
        }
        goods.setIsMarketable("0");
        goodsMapper.updateById(goods);

        //sku下架
        Item item = new Item();
        item.setStatus("2");
        UpdateWrapper<Item> wrapper = new UpdateWrapper<>();
        wrapper.eq("goods_id", id);
        itemMapper.update(item, wrapper);
    }

    /**
     * 商品还原
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reductionMarkble(Long id) {
        //通过id查询
        Goods goods = goodsMapper.selectById(id);
        //判断商品是否存在
        if (goods == null) {
            throw new RuntimeException("商品不存在");
        }
        goods.setIsDelete("0");
        goodsMapper.updateById(goods);

        //sku的还原
        Item item = new Item();
        item.setStatus("2");
        UpdateWrapper<Item> wrapper = new UpdateWrapper<>();
        wrapper.eq("goods_id", id);
        itemMapper.update(item, wrapper);
    }
}
